AP Unit 2.2
Lab will perform alterations on images, manipulate RGB values, and reduce the number of pixels. College Board requires you to learn about Lossy and Lossless compression.
- Enumerate "Data" Big Idea from College Board
- Image Files and Size
- Python Libraries and Concepts used for Jupyter and Files/Directories
- Reading and Encoding Images (2 implementations follow)
- Data Structures, Imperative Programming Style, and working with Images
- Data Structures and OOP
- Additionally, review all the imports in these three demos. Create a definition of their purpose, specifically these ...
- Hacks

Enumerate "Data" Big Idea from College Board
Some of the big ideas and vocab that you observe, talk about it with a partner ...
- "Data compression is the reduction of the number of bits needed to represent data"
- "Data compression is used to save transmission time and storage space."
- "lossy data can reduce data but the original data is not recovered"
- "lossless data lets you restore and recover"
The Image Lab Project contains a plethora of College Board Unit 2 data concepts. Working with Images provides many opportunities for compression and analyzing size.
Image Files and Size
Here are some Images Files. Download these files, load them into
imagesdirectory under _notebooks in your Blog. - Clouds Impression
Describe some of the meta data and considerations when managing Image files. Describe how these relate to Data Compression ...
- File Type, PNG and JPG are two types used in this lab
- Size, height and width, number of pixels
- Visual perception, lossy compression
Python Libraries and Concepts used for Jupyter and Files/Directories
Introduction to displaying images in Jupyter notebook
IPython
Support visualization of data in Jupyter notebooks. Visualization is specific to View, for the web visualization needs to be converted to HTML.
pathlib
File paths are different on Windows versus Mac and Linux. This can cause problems in a project as you work and deploy on different Operating Systems (OS's), pathlib is a solution to this problem.
- What are commands you use in terminal to access files?
- With terminal, we can acess files with a number of commands, such as:- cd, which changes the directory to a new folder - ls, which lists all the files and folders in the current directory
- pwd, which displays the current directory
- sudo "filename", which, in some cases, can open a file in terminal to edit files
- mc, which, in some places, opens a more user friendly file editor, which I personally love
- rm, which removes a file from a directory
- cp, which copies a file into a directory
- What are the command you use in Windows terminal to access files?
- I use commands such as:
- cd, which changes the directory to a new folder
- dir, which lists all the files and folders in the current directory
- pwd, which displays the current directory
- type "filename", which, in some cases, can open a file in terminal to edit files
- del, which removes a file from a directory
- copy, which copies a file into a directory
- rmdir, which removes a directory
- move, which moves a file from one directory to another
- What are some of the major differences?
- While at the end of the day, these commands achieve the same purpose, but windows has more casual user-friendly names for their commands than Linux or Unix. For example, del is mroe user friendly than rm, and copy is more understandable than cp.
Provide what you observed, struggled with, or leaned while playing with this code.
- Why is path a big deal when working with images?
- If you have an image in an inacessible path that is not in a root directory of the path that the code is in, the code cannot find the image
- In addition, the path must be correct in the code, or you will face an error, as the file isn't found.
- How does the meta data source and label relate to Unit 5 topics?
- Unit Five is all about lists and traversals. meta data source and label can be stored in lists, and iterating through the lists is extremely helpful, especially when you have many images that you'd like to go through and change.
- Look up IPython, describe why this is interesting in Jupyter Notebooks for both Pandas and Images?
- This is interesting because...
from IPython.display import Image, display
from pathlib import Path # https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
# prepares a series of images
def image_data(path=Path("images/"), images=None): # path of static images is defaulted
if images is None: # default image
images = [
{'source': "Peter Carolin", 'label': "Clouds Impression", 'file': "clouds-impression.png"},
{'source': "Peter Carolin", 'label': "Lassen Volcano", 'file': "lassen-volcano.jpg"},
{'source': "Peter Carolin", 'label': "Strikers", 'file': "unnamed.png"}
]
for image in images:
# File to open
image['filename'] = path / image['file'] # file with path
return images
def image_display(images):
for image in images:
display(Image(filename=image['filename']))
# Run this as standalone tester to see sample data printed in Jupyter terminal
if __name__ == "__main__":
# print parameter supplied image
green_square = image_data(images=[{'source': "Internet", 'label': "Green Square", 'file': "green-square-16.png"}])
image_display(green_square)
# display default images from image_data()
default_images = image_data()
image_display(default_images)
Reading and Encoding Images (2 implementations follow)
PIL (Python Image Library)
Pillow or PIL provides the ability to work with images in Python. Geeks for Geeks shows some ideas on working with images.
base64
Image formats (JPG, PNG) are often called *Binary File formats, it is difficult to pass these over HTTP. Thus, base64 converts binary encoded data (8-bit, ASCII/Unicode) into a text encoded scheme (24 bits, 6-bit Base64 digits). Thus base64 is used to transport and embed binary images into textual assets such as HTML and CSS.- How is Base64 similar or different to Binary and Hexadecimal?
- Base 64 is similar in that it represents decimal numbers, but using a different number as the base - Like how 4 binary bits represents 1 hexadecimal digit, 6 binary bits(or 2 octal bits) represent one digit in Base64 - It's different because binary, and decimal numbers are represented by only decimal digits. Hexadecimal can be represented by decimal digits and uppercase letters. However, 64 cannot be represented with decimal digits and numbers, and requires decimal numbers, uppercase letters, lowercase letters, and "*" and "/"
- Translate first 3 letters of your name to Base64.
- "C" = B1
- "h" = E8
- "i" = E9
- ### numpy Numpy is described as "The fundamental package for scientific computing with Python". In the Image Lab, a Numpy array is created from the image data in order to simplify access and change to the RGB values of the pixels, converting pixels to grey scale.
io, BytesIO
Input and Output (I/O) is a fundamental of all Computer Programming. Input/output (I/O) buffering is a technique used to optimize I/O operations. In large quantities of data, how many frames of input the server currently has queued is the buffer. In this example, there is a very large picture that lags.
- Where have you been a consumer of buffering?
- Buffering is a technique that is used in many areas of computing, such as streaming audio and video, downloading files, and network communications. When data is being transferred, it is often more efficient to transfer it in larger chunks rather than in individual bytes. This is where buffering comes in - it allows the data to be collected in memory before it is transferred to its destination.
- From your consumer experience, what effects have you experienced from buffering?
- One common effect of buffering is a delay or lag in the delivery of data. This delay is often caused by the time it takes for data to be collected in the buffer before it is transmitted to the destination. However, buffering can also improve the overall efficiency of data transfer by reducing the number of smaller transfers required.
- How do these effects apply to images?
- When it comes to images, buffering can affect their display by causing a delay or lag in their rendering. This can be especially noticeable for large images or images that require a lot of processing. However, buffering can also improve the overall performance of image processing by allowing for larger chunks of data to be processed at once.
Data Structures, Imperative Programming Style, and working with Images
Introduction to creating meta data and manipulating images. Look at each procedure and explain the the purpose and results of this program. Add any insights or challenges as you explored this program.
- Does this code seem like a series of steps are being performed?
- the code does seem like a seires of steps are performed. Albeit the groups of steps are in a different order due to the heavy reliance of functions in this program.
- Describe Grey Scale algorithm in English or Pseudo code?
- The code includes several functions that prepare a series of images, scales images, converts images to base64, sets properties of images, and creates grey scale base64 representation of images. The main block of the code uses these functions to display meta data, scaled view, and grey scale for each image.
- see for pseudocode below:-
- Describe scale image? What is before and after on pixels in three images?
- Before and after, the image retains its quality, but after grayscale is applied, it's black and white. All the colors have drastically changed other than one of the pictures I added which is a drawing, so its color didn't change much.
- Is scale image a type of compression? If so, line it up with College Board terms described?
- Scale image is a type of compression, as the color of the pixels is compressed to be only represented in grayscale. Collegeboard defined compression as when the emount or deetail of data is lowered so the data can fit into a smaller spce, taking up less memory.
from IPython.display import HTML, display
from pathlib import Path # https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
from PIL import Image as pilImage # as pilImage is used to avoid conflicts
from io import BytesIO
import base64
import numpy as np
# prepares a series of images
def image_data(path=Path("images/"), images=None): # path of static images is defaulted
if images is None: # default image
images = [
{'source': "Internet", 'label': "Green Square", 'file': "green-square-16.png"},
{'source': "Peter Carolin", 'label': "Clouds Impression", 'file': "clouds-impression.png"},
{'source': "Peter Carolin", 'label': "Lassen Volcano", 'file': "lassen-volcano.jpg"},
{'source': "Peter Carolin", 'label': "Strikers", 'file': "unnamed.png"}
]
for image in images:
# File to open
image['filename'] = path / image['file'] # file with path
return images
# Large image scaled to baseWidth of 320
def scale_image(img):
baseWidth = 320
scalePercent = (baseWidth/float(img.size[0]))
scaleHeight = int((float(img.size[1])*float(scalePercent)))
scale = (baseWidth, scaleHeight)
return img.resize(scale)
# PIL image converted to base64
def image_to_base64(img, format):
with BytesIO() as buffer:
img.save(buffer, format)
return base64.b64encode(buffer.getvalue()).decode()
# Set Properties of Image, Scale, and convert to Base64
def image_management(image): # path of static images is defaulted
# Image open return PIL image object
img = pilImage.open(image['filename'])
# Python Image Library operations
image['format'] = img.format
image['mode'] = img.mode
image['size'] = img.size
# Scale the Image
img = scale_image(img)
image['pil'] = img
image['scaled_size'] = img.size
# Scaled HTML
image['html'] = '<img src="data:image/png;base64,%s">' % image_to_base64(image['pil'], image['format'])
# Create Grey Scale Base64 representation of Image
def image_management_add_html_grey(image):
# Image open return PIL image object
img = image['pil']
format = image['format']
img_data = img.getdata() # Reference https://www.geeksforgeeks.org/python-pil-image-getdata/
image['data'] = np.array(img_data) # PIL image to numpy array
image['gray_data'] = [] # key/value for data converted to gray scale
# 'data' is a list of RGB data, the list is traversed and hex and binary lists are calculated and formatted
for pixel in image['data']:
# create gray scale of image, ref: https://www.geeksforgeeks.org/convert-a-numpy-array-to-an-image/
average = (pixel[0] + pixel[1] + pixel[2]) // 3 # average pixel values and use // for integer division
if len(pixel) > 3:
image['gray_data'].append((average, average, average, pixel[3])) # PNG format
else:
image['gray_data'].append((average, average, average))
# end for loop for pixels
img.putdata(image['gray_data'])
image['html_grey'] = '<img src="data:image/png;base64,%s">' % image_to_base64(img, format)
# Jupyter Notebook Visualization of Images
if __name__ == "__main__":
# Use numpy to concatenate two arrays
images = image_data()
# Display meta data, scaled view, and grey scale for each image
for image in images:
image_management(image)
print("---- meta data -----")
print(image['label'])
print(image['source'])
print(image['format'])
print(image['mode'])
print("Original size: ", image['size'])
print("Scaled size: ", image['scaled_size'])
print("-- original image --")
display(HTML(image['html']))
print("--- grey image ----")
image_management_add_html_grey(image)
display(HTML(image['html_grey']))
print()
Data Structures and OOP
Most data structures classes require Object Oriented Programming (OOP). Since this class is lined up with a College Course, OOP will be talked about often. Functionality in remainder of this Blog is the same as the prior implementation. Highlight some of the key difference you see between imperative and oop styles.
- Read imperative and object-oriented programming on Wikipedia
- Consider how data is organized in two examples, in relations to procedures
- Look at Parameters in Imperative and Self in OOP
Additionally, review all the imports in these three demos. Create a definition of their purpose, specifically these ...
- PIL
- numpy
- base64
from PIL import Image
def greenscale(input_file):
# Open the input image
with Image.open(input_file) as img:
# Convert the image to greenscale
greenscale_img = img.convert("L").convert("RGB")
greenscale_img = Image.merge("RGB", (greenscale_img.split()[0], img.split()[1], greenscale_img.split()[0]))
# Save the greenscale image
display(greenscale_img)
if __name__ == "__main__":
# Example usage
images = [
{'source': "Internet", 'label': "Green Square", 'file': "green-square-16.png"},
{'source': "Peter Carolin", 'label': "Clouds Impression", 'file': "clouds-impression.png"},
{'source': "Peter Carolin", 'label': "Lassen Volcano", 'file': "lassen-volcano.jpg"},
{'source': "Peter Carolin", 'label': "Strikers", 'file': "unnamed.png"}
]
for i in images:
greenscale("images/"+i["file"])
Hacks
Early Seed award
- Add this Blog to you own Blogging site.
- In the Blog add a Happy Face image.
- Have Happy Face Image open when Tech Talk starts, running on localhost. Don't tell anyone. Show to Teacher.
AP Prep
- In the Blog add notes and observations on each code cell that request an answer.
- In blog add College Board practice problems for 2.3
-
- Choose 2 images, one that will more likely result in lossy data compression and one that is more likely to result in lossless data compression. Explain.
- Lossy:
![]()
- Lossless:
![]()
- The lossy image is more lossy because of the amount of different shades, colors,a nd details in small places. If this image was compressed to a smaller size, then a lot of the detail would go away as it cannot be represented in such a small number of pixels. On the other hand, the lossless image is simple, and it won't lose any detail as it gets smaller, at least to a certain point. Project Addition
- If your project has images in it, try to implement an image change that has a purpose. (Ex. An item that has been sold out could become gray scale)
Pick a programming paradigm and solve some of the following ...
- Numpy, manipulating pixels. As opposed to Grey Scale treatment, pick a couple of other types like red scale, green scale, or blue scale. We want you to be manipulating pixels in the image.
- see up for greenscale
- Binary and Hexadecimal reports. Convert and produce pixels in binary and Hexadecimal and display.
- Compression and Sizing of images. Look for insights into compression Lossy and Lossless. Look at PIL library and see if there are other things that can be done.
- There are many effects you can do as well with PIL. Blur the image or write Meta Data on screen, aka Title, Author and Image size.
- Describe scale image? What is before and after on pixels in three images?
-
Pick a programming paradigm and solve some of the following ...